/**
 * 
 */
package uk.ac.lkl.lpp;

import java.io.File;
import java.io.IOException;

//import java.util.ArrayDeque; oops, 1.6
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.logging.Level;

import java.util.prefs.Preferences;

import javax.swing.filechooser.FileFilter;

/**
 * This class provides some file and persistance services to the application.
 * It also provides access to persistant user prefernces such as recently opened files, etc. 
 * All relevant methods are static.
 * @author yish
 *
 */
public final class FileUtils {
	private static final Logger logger = Logger.getLogger("uk.ac.lkl.lpp");

	/**
	 * never instanstiate me.
	 */
	private FileUtils(){}
	
	public static final String RECENT_FILE_COUNT_KEY = "recentFileCount";
	public static final int RECENT_FILE_COUNT_DEFAULT = 5;
	public static final String RECENT_FILE_KEY = "recentFile.";
	public static final String CURRENT_DIR_KEY = "currentDirectory";
	
	/*
	 * how many recent files do we track?
	 */
	private static int recentFileCount = -1;
	
	/*
	 * list of recent files 
	 */
	private static ArrayList<String> recentFiles = new ArrayList<String>(); 
//	private static ArrayDeque<String> recentFiles = new ArrayDeque<String>(); 
	
	/**
	 * where we store user preferences and application properties between sessions.
	 */
	private static final Preferences appPrefs = 
		Preferences.userNodeForPackage(LondonPedagogyPlanner.class);
	
	
    /**
     * filter for .lpp files
     */
    public final static FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            if (file.isDirectory())
                return true;
            String name = file.getName();
            return name.endsWith(".lpp");
        }

        public String getDescription() {
            return "London Pedagogy Planner (lpp) files";
        }
    };
	/**
	 * get an application preference.
	 * @param key what to look for
	 * @param def wht to return if its blanc
	 * @return
	 */
	public static String getPreference(String key, String def) {
		return appPrefs.get(key, def);
	}
	
	/**
	 * set an application preference
	 * @param key
	 * @param value
	 */
	public static void setPreference(String key, String value) {
		appPrefs.put(key, value);
	}
	
	public static int getRecentFileCount(){
		if (recentFileCount < 0) loadRecentFiles();
		return recentFileCount;
	}
	
	public static String[] recentFiles() {
		if (recentFileCount < 0) loadRecentFiles();
		return (String[])recentFiles.toArray();
	}
	
	/**
	 * read the recent files from prefs.
	 *
	 */
	private static void loadRecentFiles() {
		// load recent files count
		recentFileCount = Integer.parseInt(getPreference(RECENT_FILE_COUNT_KEY,
				String.valueOf(RECENT_FILE_COUNT_DEFAULT)));
		
		// load file names
		for (int i=0; i < recentFileCount; i++) {
			recentFiles.add(getPreference(RECENT_FILE_KEY+i,""));
		}
		
	}
	
	/**
	 * save recent files to prefs.
	 */
	public static void saveRecentFiles() {
		if (recentFileCount < 0) return;
		String[] files = recentFiles();
		for (int i=0; i < files.length; i++) {
			if (files[i] == null) return;
			setPreference(RECENT_FILE_KEY+i,files[i]);
		}		
		
	}
	
	/**
	 * add a file to the recent list.
	 */
	public static void addToRecentFiles(String file){
		if (recentFileCount < 0) loadRecentFiles();
		recentFiles.add(file);
	}
	
	/**
	 * get current directory
	 */
	public static String getCurrentDirectory() {
		return getPreference(CURRENT_DIR_KEY,System.getProperty("user.dir"));
	}
	
	/**
	 * set current directory
	 */
	public static void setCurrentDirectory(String dirName) {
		setPreference(CURRENT_DIR_KEY,dirName);
	}
	
	/**
	 * set current directory
	 */
	public static void setCurrentDirectory(File f) {
		try {
			if (f.isDirectory()) {
				setCurrentDirectory(f.getCanonicalFile());
			} else {
				setCurrentDirectory(f.getParentFile().getCanonicalPath());
			}
		} catch (IOException e) {
			logger.log(Level.FINE, "failed to set current directory", e);
		}
	}
	
	/**
	 * save all that needs saving, call this on system.exit
	 */
	public static void onExit() {
		saveRecentFiles();
	}

}
